package org.groupg.filetodb;

import com.lmax.disruptor.EventHandler;
import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicInteger;

public class CsvBatchHandler implements EventHandler<CsvBatchEvent> {
    private static final Logger log = LoggerFactory.getLogger(CsvBatchHandler.class);

    private final String sql;
    private final DataSource dataSource;
    private final QueryRunner queryRunner;

    public CsvBatchHandler(String sql, DataSource dataSource) {
        this.sql = sql;
        this.dataSource = dataSource;
        this.queryRunner = new QueryRunner(dataSource);
    }
    public static final AtomicInteger count = new AtomicInteger(0);
    @Override
    public void onEvent(CsvBatchEvent event, long sequence, boolean endOfBatch) {
        try {
            log.info("Processing batch {} with {} records", event.getBatchNumber(), event.getRecords().size());
            // 实际处理逻辑...
            count.getAndAdd(event.getRecords().size());
            getQueryRunner().batch(getSql(),event.getRecordsArray());
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        } finally {
            event.clear();  // 重要：清理引用
        }
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public String getSql() {
        return sql;
    }

    public QueryRunner getQueryRunner() {
        return queryRunner;
    }
}
